<template>
  <el-input placeholder="请配置人员角色信息" @click="openModal"
            type="textarea" readonly v-model="roleNames"/>
  <FModal header="人员角色信息" ref="refFModal" @ok="ok">
    <FPage>
      <template #header>
        <el-button icon="add" round type="primary"
                   @click="addNew" style="margin: 5px 0">添加
        </el-button>
      </template>

      <div class="user-role-page-body">
        <div v-for="(item, index) in roleList" :key="item" class="user-role-item">
          <div class="user-role">
            <el-text truncated class="user-role-item-label">
              部门/单位
            </el-text>

            <el-tree-select
              v-model="item.unitId"
              :data="unitTrees" default-expand-all
              check-strictly node-key="id"
              :props="defaultProps" style="flex: 0.5"
              :render-after-expand="false"
              @change="() => departChange(item)"
            />

            <el-text v-if="item.departRole === true || item.departRole === false"
                     truncated class="user-role-item-label">
              角色
            </el-text>

            <el-select v-if="item.departRole === true" @change="() => roleChange(item, departRoleList)"
                       v-model="item.roleId">
              <el-option v-for="item in departRoleList"
                         :key="item.id" :label="item.roleName" :value="item.id"/>
            </el-select>
            <el-select v-else-if="item.departRole === false"
                       v-model="item.roleId" @change="() => roleChange(item, unitRoleList)">
              <el-option v-for="item in unitRoleList"
                         :key="item.id" :label="item.roleName" :value="item.id"/>
            </el-select>
            <el-popconfirm confirm-button-text="确定" cancel-button-text="取消"
                           title="确定删除吗?" @confirm.stop="() => removeUserRole(index)">
              <template #reference>
                <el-button style="margin-left: 5px" type="warning"
                           round circle icon="remove"/>
              </template>
            </el-popconfirm>
          </div>
        </div>
      </div>
    </FPage>
  </FModal>
</template>
<script setup>
import FModal from '@/components/FModal/index.vue';
import {computed, nextTick, ref, shallowRef} from 'vue';
import {findListTitle, isEmpty, listToTrees, real, treesForeach} from '@/utils/CommonUtils';
import FPage from '@/components/layout/FPage.vue';
import {getAction} from '@/request/BaseRequest';
import {ElMessage} from 'element-plus';

const props = defineProps({
  modelValue: {
    type: Array,
    default: () => [],
  },
  unitData: {
    type: Object,
    default: () => ({}),
  }
});
const emits = defineEmits(['update:modelValue']);
const refFModal = shallowRef();
const roleList = ref([]);
const defaultProps = {
  children: 'children',
  label: 'unitName',
};
const loading = shallowRef(false);
const roleNames = computed(() => {
  let value = real(props.modelValue);
  if (isEmpty(value)) return undefined;
  let list = value.map(v => v.unitName + ":" + v.roleName);
  return list.toString();
});
const unitTrees = shallowRef([]);
const departRoleList = shallowRef([]);
const unitRoleList = shallowRef([]);

function ok() {
  if (checkData()) {
    let list = JSON.parse(JSON.stringify(real(roleList)));
    emits('update:modelValue', list);
    refFModal.value.close();
  }
}

function checkData() {
  let list = real(roleList);
  if (isEmpty(list)) {
    list = [];
  }

  for (let i = 0; i < list.length; i++) {
    let item = list[i];
    if (isEmpty(item.unitId) || isEmpty(item.roleId)) {
      ElMessage({
        message: '请将必填项填写完整',
        type: 'warning',
      });
      return false;
    }
  }
  return true;
}

function openModal() {
  refFModal.value.open();
  nextTick(() => {
    roleList.value = real(props.modelValue);
    loadDeaprts();
    loadRoles();
  });
}

function loadDeaprts() {
  loading.value = true;
  getAction('/sys/unit/loadDepatrsByPath',
    {path: props.unitData.path}).then(data => {
    loading.value = false;
    if (data.success) {
      let result = data.result;
      setUnitTrees(result);
    }
  });
}

function setUnitTrees(list) {
  let trees = listToTrees(list);
  if (isEmpty(trees)) {
    trees = [];
  }
  unitTrees.value = trees;
}

function roleChange(item, list) {
  nextTick(() => {
    item.roleName = findListTitle(item.roleId, real(list), 'roleName');
  });
}

function departChange(item) {
  treesForeach(real(unitTrees), node => {
    if (node.id === item.unitId) {
      if (node.type + '' === '0') {
        item.departRole = false;
      } else {
        item.departRole = true;
      }
      item.unitName = node.unitName;
    }
  });
  item.roleId = undefined;
  item.roleName = undefined;
}

function removeUserRole(index) {
  roleList.value.splice(index, 1);
}

function loadRoles() {
  departRoleList.value = [];
  unitRoleList.value = [];

  loading.value = true;
  getAction('/sys/role/loadUnitRoles',
    {unitId: props.unitData.id}).then(data => {
    loading.value = false;
    if (data.success) {
      let result = data.result;
      setRoles(result);
    }
  });
}

function setRoles(result) {
  if (isEmpty(result)) {
    result = [];
  }
  let list1 = [];
  let list2 = [];
  result.forEach(role => {
    if (role.departRole) {
      list1.push(role);
    } else {
      list2.push(role);
    }
  });

  departRoleList.value = list1;
  unitRoleList.value = list2;
}

function addNew() {
  roleList.value.push(createEmptyRole());
}

function createEmptyRole() {
  return {
    roleId: undefined,
    roleName: undefined,
    unitId: undefined,
    unitName: undefined,
    departRole: undefined,
  };
}

</script>
<script>
export default {
  name: 'UserRoleListModal'
};
</script>
<style>

.user-role-page-body {
}

.f-modal-fullscreen-body .user-role-page-body {
  height: 100%;
}

.f-page-body .user-role-page-body {
  height: 500px;
}

.user-role-item {
  background: white;
}

.user-role {
  padding: 10px 10px;
  display: flex;
  justify-content: center;
  align-items: center;
  border-width: 0 2px 0 2px;
  border-color: #f0f2f5;
  border-style: solid;
}

.user-role-item-label {
  width: 70px;
  text-align: center;
}
</style>
